package com.cicigodd.brick.plug.annotation.repeatsubmit;

import com.cicigodd.brick.plug.common.exception.BusinessException;
import com.cicigodd.brick.plug.common.utils.AuthUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author cicigodd
 * @date 2022-10-20 11:08
 */
@Component
@Aspect
@Order(100)
public class FilterRepeat {

    @Resource
    private RedisTemplate redisTemplate;

    // 定义 注解 类型的切点
    @Pointcut("@annotation(com.cicigodd.brick.plug.annotation.repeatsubmit.RepeatSubmit)")
    public void arrPointcut() {
    }

    // 实现过滤重复请求功能
    @Around("arrPointcut()")
    public Object arrBusiness(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = AuthUtil.getToken();
        String key = "REQUEST_" + token + "_" + request.getRequestURI();
        // 判断是否是重复的请求
        if (!redisTemplate.opsForValue().setIfAbsent(key, 1)) {
            // 返回异常需要有统一异常捕获
            throw new BusinessException("重复请求");
        }
        try {
            Object obj = joinPoint.proceed();
            redisTemplate.delete(key);
            return obj;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return "error";
        }
    }

}
